#include "MarketService.h"
#include "EventEngine.h"
#include "RedisWrapper.h"
#include "ContractManager.h"
#include "MarketDataEngine.h"
#include "HistoryDataEngine.h"
#include "LogManager.h"
#include <QThread>
#include <QTimer>
#include <QFile>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QCoreApplication>
#include <fmt/format.h>

namespace Market {

MarketService::MarketService(QObject* parent) : QObject(parent) {
}

MarketService::~MarketService() {
    stop();
}

bool MarketService::init(const QString& configPath) {
    if (m_initialized) {
        return true;
    }
    
    m_configPath = configPath;
    MLOG_INFO("market", "Initializing market service with config path: {}", configPath.toStdString());
    
    // 初始化合约管理器
    QString contractConfigFile = m_configPath + "/contracts.json";
    MLOG_INFO("market", "Loading contracts from: {}", contractConfigFile.toStdString());
    if (!CONTRACT_MGR->init(contractConfigFile)) {
        MLOG_ERROR("market", "Failed to initialize contract manager");
        return false;
    }
    
    // 初始化Redis
    QString redisConfigFile = m_configPath + "/redis.json";
    MLOG_INFO("market", "Loading Redis config from: {}", redisConfigFile.toStdString());
    if (!REDIS_WRAPPER->init(redisConfigFile)) {
        MLOG_ERROR("market", "Failed to initialize Redis wrapper");
        return false;
    }

    // 初始化行情引擎
    QString marketConfigFile = m_configPath + "/market.json";
    MLOG_INFO("market", "Loading market config from: {}", marketConfigFile.toStdString());
    // 检查配置文件是否存在
    if (!QFile::exists(marketConfigFile)) {
        MLOG_ERROR("market", "Market config file not found: {}", marketConfigFile.toStdString());
        return false;
    }
    if (!MARKET_ENGINE->init(marketConfigFile)) {
        MLOG_ERROR("market", "Failed to initialize market data engine");
        return false;
    }

    // 连接行情引擎信号
    connect(MARKET_ENGINE, &MarketDataEngine::connected, this, [this]() {
        MLOG_TRACE("market", "Market engine connected");
        Event event(EventType::MARKET_CONNECTED);
        EVENT_ENGINE->postEvent(std::move(event));
    });

    connect(MARKET_ENGINE, &MarketDataEngine::disconnected, this, [this](int reason) {
        MLOG_INFO("market", "Market engine disconnected, reason: {}", reason);
        Event event(EventType::MARKET_DISCONNECTED);
        event.data() = reason;
        EVENT_ENGINE->postEvent(std::move(event));
    });

    connect(MARKET_ENGINE, &MarketDataEngine::loginSuccess, this, [this]() {
        MLOG_TRACE("market", "Market engine login success");
        // 读取需要订阅的合约列表
        QFile file(m_configPath + "/market.json");
        if (file.open(QIODevice::ReadOnly)) {
            QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
            QJsonObject obj = doc.object();
            QJsonArray subscribes = obj["Subscribes"].toArray();
            
            std::vector<std::string> symbols;
            for (const auto& symbol : subscribes) {
                symbols.push_back(symbol.toString().toStdString());
            }
            
            if (!symbols.empty()) {
                MLOG_INFO("market", "Subscribing to {} symbols", symbols.size());
                MARKET_ENGINE->batchSubscribe(symbols);
            }
        }
        file.close();
    });

    // 注册事件处理器
    EVENT_ENGINE->registerHandler(EventType::TICK,
        std::bind(&MarketService::handleTick, this, std::placeholders::_1));
    EVENT_ENGINE->registerHandler(EventType::BAR,
        std::bind(&MarketService::handleBar, this, std::placeholders::_1));
    EVENT_ENGINE->registerHandler(EventType::MARKET_CONNECTED,
        std::bind(&MarketService::handleMarketConnected, this, std::placeholders::_1));
    EVENT_ENGINE->registerHandler(EventType::MARKET_DISCONNECTED,
        std::bind(&MarketService::handleMarketDisconnected, this, std::placeholders::_1));

    m_initialized = true;
    MLOG_TRACE("market", "Market service initialized successfully");
    return true;
}

void MarketService::handleSyncFailed(const QString& error) {
    MLOG_ERROR("market", "History data sync failed: {}", error.toStdString());
    stop();
}

void MarketService::start() {
    if (!m_initialized) {
        MLOG_ERROR("market", "Market service not initialized");
        return;
    }

    if (m_running) {
        MLOG_WARN("market", "Market service already running");
        return;
    }

    // 启动事件引擎
    EVENT_ENGINE->start();
    MLOG_TRACE("market", "Event engine started");

    // 启动行情引擎
    MARKET_ENGINE->start();
    MLOG_TRACE("market", "Market engine started");

    // 设置每日定时器
    if (!m_dailyTimer) {
        m_dailyTimer = new QTimer(this);
        connect(m_dailyTimer, &QTimer::timeout, this, &MarketService::handleDailyTask);
    }

    // 计算下一个任务时间点
    QTime targetTime = QTime::fromString("20:30:00", "HH:mm:ss");
    QTime currentTime = QTime::currentTime();
    int msecToTarget;

    if (currentTime < targetTime) {
        msecToTarget = currentTime.msecsTo(targetTime);
    } else {
        msecToTarget = currentTime.msecsTo(QTime(23, 59, 59)) + 1000 + QTime(0, 0, 0).msecsTo(targetTime);
    }

    m_dailyTimer->start(msecToTarget);
    MLOG_TRACE("market", "Daily timer set to trigger in {} ms", msecToTarget);

    m_running = true;
    MLOG_TRACE("market", "Market service started successfully");
}

void MarketService::stop() {
    if (!m_running) {
        return;
    }
    
    MLOG_INFO("market", "Stopping market service...");
    
    if (m_dailyTimer) {
        m_dailyTimer->stop();
    }

    MARKET_ENGINE->stop();
    HISTORY_ENGINE->stopSync();
    
    m_running = false;
}

void MarketService::handleTick(const Event& event) {
    try {
        const auto& tick = std::any_cast<WTSTickStruct>(event.data());
        MLOG_DEBUG("market", "Processing tick: {}.{} @ {} (vol: {}, oi: {})", 
            tick.exchg, tick.code, tick.price, tick.volume, tick.open_interest);
        
        // 发送Tick数据到Redis
        REDIS_WRAPPER->publishTick(tick);

        // 处理Bar生成
        BAR_GENERATOR->onTick(tick);
    }
    catch (const std::exception& e) {
        MLOG_ERROR("market", "Failed to handle tick event: {}", e.what());
    }
}

void MarketService::handleBar(const Event& event) {
    try {
        const auto& barData = std::any_cast<BarData>(event.data());
        const auto& [symbol, bar] = barData;
        
        // 获取合约信息
        auto contract = CONTRACT_MGR->getContract(symbol);
        if (contract.m_strCode.empty()) {
            MLOG_ERROR("market", "Contract not found for symbol: {}", symbol);
            return;
        }
        
        MLOG_INFO("market", "Received {} bar: O={}, H={}, L={}, C={}, V={}, Time={}",
            symbol, bar.open, bar.high, bar.low, bar.close, bar.vol,
            QDateTime::fromSecsSinceEpoch(bar.time).toString("HH:mm:ss").toStdString());
        
        // 直接发送Bar数据到Redis
        REDIS_WRAPPER->publishBar(bar, contract.m_strExchg, contract.m_strCode, TrPeriod::M1);
    }
    catch (const std::exception& e) {
        MLOG_ERROR("market", "Failed to handle bar event: {}", e.what());
    }
}

void MarketService::handleMarketConnected(const Event& event) {  
    // 在这里添加Bar生成器的初始化
    try {
        // 读取需要订阅的合约列表
        QFile file(m_configPath + "/market.json");
        if (file.open(QIODevice::ReadOnly)) {
            QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
            QJsonObject obj = doc.object();
            QJsonArray subscribes = obj["Subscribes"].toArray();
            
            // 为每个合约添加不同周期的Bar生成器
            for (const auto& symbol : subscribes) {
                std::string code = symbol.toString().toStdString();
                
                // 获取合约信息以确定交易所
                auto contract = CONTRACT_MGR->getContract(code);
                if (contract.m_strCode.empty()) {
                    MLOG_ERROR("market", "Contract not found for code: {}", code);
                    continue;
                }
                
                // 添加1分钟K线生成器
                BAR_GENERATOR->addGenerator(symbol.toString(), TrPeriod::M1, QString::fromStdString(contract.m_strSession),
                    [this](const std::string& symbol, const WTSBarStruct& bar) {
                        //REDIS_WRAPPER->publishBar(bar, exchg, code, TrPeriod::M1);
                        
                    });
            
            }
        }
        file.close();
    }
    catch (const std::exception& e) {
        MLOG_ERROR("market", "Failed to initialize bar generators: {}", e.what());
    }
}

void MarketService::handleMarketDisconnected(const Event& event) {
    MLOG_INFO("market", "Market disconnected");
}

void MarketService::handleDailyTask() {
    try {
        MLOG_INFO("market", "Executing daily task");
        
        // 重新设置定时器为24小时
        m_dailyTimer->start(24 * 60 * 60 * 1000);
        
        // 在这里添加每日任务的处理
        // ...
        
    }
    catch (const std::exception& e) {
        MLOG_ERROR("market", "Failed to handle daily task: {}", e.what());
    }
}

} // namespace Market